from flask import Blueprint, request
from flask.views import MethodView
from extension import db, CORS
from models import User

user_bp = Blueprint('user', __name__, url_prefix='/admins/users')


class UserApi(MethodView):

    def get(self, username):
        # 无参
        if not username:
            users: [User] = User.query.all()
            results = [
                {
                    'user_login_cardID': user.cardID,
                    'user_login_username': user.username,
                    'user_login_password': user.password,
                    'user_login_role': user.role,
                    'user_login_money': user.money
                } for user in users
            ]
            return {
                'status': 'success',
                'message': '用户账号密码信息已返回',
                'results': results
            }
        # 有参,模糊查找
        users: [User] = User.query.filter(User.username.like('%' + username + '%')).all()
        results = [
            {
                'user_login_cardID': user.cardID,
                'user_login_username': user.username,
                'user_login_password': user.password,
                'user_login_role': user.role,
                'user_login_money': user.money
            } for user in users
        ]
        return {
            'status': 'success',
            'message': '用户信息查询成功',
            'results': results
        }

    def post(self):
        form = request.json
        user = User()
        user.username = form.get('user_login_username')
        user.password = form.get('user_login_password')
        user.role = form.get('user_login_role')
        user.money = form.get('user_login_money')
        try:
            db.session.add(user)
            db.session.commit()
            return {
                'status': 'success',
                'message': '用户添加成功'
            }
        except Exception as e:
            db.session.rollback()
            return {
                'status': 'fault',
                'message': '用户添加失败'
            }

    def delete(self, user_cardID):
        user = User.query.get(user_cardID)
        try:
            db.session.delete(user)
            db.session.commit()
            return {
                'status': 'success',
                'message': '用户删除成功'
            }
        except Exception as e:
            db.session.rollback()
            return {
                'status': 'fault',
                'message': '用户删除失败'
            }

    def put(self, user_cardID):
        user: User = User.query.get(user_cardID)
        user.username = request.json.get('user_login_username')
        user.password = request.json.get('user_login_password')
        user.role = request.json.get('user_login_role')
        user.money = request.json.get('user_login_money')
        db.session.commit()
        return {
            'status': 'success',
            'message': '用户信息修改成功'
        }


user_view = UserApi.as_view('user_api')
